//
//  WSManager+Notifications.m
//  mUBB
//
//  Created by Cosmin Stirbu on 5/11/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "WSManager+Notifications.h"
#import "SubscribeHandler.h"
#import "UnsubscribeHandler.h"
#import "ConfigurationManager.h"

@implementation WSManager (Notifications)

- (Ticket *)subscribeForNotificationsForCourse:(Course *)course delegate:(id<NotificationsProtocol>)delegate {
    // Ticket
    Ticket *ticket = [[Ticket alloc] initWithId:ticketId++];
    
    // Connection Delegate
    SubscribeHandler *subscribeHandler = [[SubscribeHandler alloc] initWithDelegate:delegate ticket:ticket];
    subscribeHandler.course = course;
    
    connectionDelegate = subscribeHandler;
    
    
    // Device Id
    NSString *deviceId = [[ConfigurationManager instance] applicationConfigValueForKey:DEVICE_ID];
    
    // JSON Data
    NSString *jsonData = [NSString stringWithFormat:@"{ \"DeviceId\" : \"%@\", \"CourseCode\":\"%@\" }", deviceId, course.courseCode];
    
    // URL
    NSString *url = [UserDefaultsManager getObjectForKey:WS_NOTIFICATION_SERVICE];
    
    // Make the request
    [self postRequestWithUrl:url body:jsonData andHeaders:nil];
    
    connectionDelegate = nil;
    
    return ticket;
}

- (Ticket *)unsubscribeForNotificationsForCourse:(Course *)course delegate:(id<NotificationsProtocol>)delegate {
    // Ticket
    Ticket *ticket = [[Ticket alloc] initWithId:ticketId++];
    
    // Connection Delegate
    connectionDelegate = [[UnsubscribeHandler alloc] initWithDelegate:delegate ticket:ticket];
    
    // Device Id
    NSString *deviceId = [[ConfigurationManager instance] applicationConfigValueForKey:DEVICE_ID];
    
    // JSON Data
    NSString *jsonData = [NSString stringWithFormat:@"{ \"DeviceId\" : \"%@\" }", deviceId];
    
    // Registration Id
    NSInteger registrationId = [[UserDefaultsManager getObjectForKey:course.courseCode] integerValue];
    
    // Url
    NSString *url = [NSString stringWithFormat:@"%@/%d",[UserDefaultsManager getObjectForKey:WS_NOTIFICATION_SERVICE], registrationId];
    
    
    // Make the request
    [self deleteRequestWithUrl:url body:jsonData andHeaders:nil];
    
    connectionDelegate = nil;
    
    return ticket;
}

@end
